import { reqLogin, reqUserInfo, reqAvatar } from '@/api/user.js'
import { setToken, getToken, removeToken } from '@/utils/auth'
export default {
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    setToken(state, val) {
      state.token = val
      setToken(val)
    },
    delToken(state) {
      state.token = ''
      state.userInfo = {}
      removeToken()
    },
    setUserInfo(state, data) {
      state.userInfo = data
    }
  },
  actions: {
    async login({ commit, dispatch }, data) {
      try {
        const { data: token } = await reqLogin(data)
        await commit('setToken', token)
        await dispatch('getUserInfo')
      } catch (error) {
        return Promise.reject(error)
      }
    },
    async getUserInfo({ commit }) {
      const { data } = await reqUserInfo()

      const { data: data1 } = await reqAvatar(data.userId)

      commit('setUserInfo', { ...data, ...data1 })
    }
  },
  namespaced: true
}
